package com.pactera.madp.service.impl;

import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import com.pactera.madp.constant.SecurityConstants;
import com.pactera.madp.model.dto.UserDto;
import com.pactera.madp.model.entity.User;
import com.pactera.madp.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;

import java.util.concurrent.TimeUnit;

/**
 * All rights Reserved, Designed By teana@sina.cn.
 *
 * @Author: Deming.Chang
 * @Email: teana@sina.cn
 * @Date: 2018/9/16 上午11:21
 * @Version: 1.0.0
 * @Copyright: 2018
 * @Description:
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Override
    public UserDto login(UserDto userDto) {
        if(StrUtil.equals("admin", userDto.getUsername()) && StrUtil.equals("123123a", userDto.getPassword())){
            userDto.setId("1" + RandomUtil.randomNumbers(5));
            userDto.setToken(RandomUtil.simpleUUID());

            redisTemplate.opsForValue().set(SecurityConstants.TOKEN_PREFIX + userDto.getToken(),
                    userDto, 300, TimeUnit.SECONDS);
            redisTemplate.opsForValue().set(SecurityConstants.USER_ID_PREFIX + userDto.getId(),
                    userDto.getToken(), 300, TimeUnit.SECONDS);

            return userDto;
        }
        return null;
    }

    @Override
    public UserDto info(String id) {
        Assert.notNull(id, "[Assertion failed] - id is required; it must not be null");

        String token = (String) redisTemplate.opsForValue().get(SecurityConstants.USER_ID_PREFIX + id);
        if(StrUtil.isNotBlank(token)){
            UserDto userDto = (UserDto) redisTemplate.opsForValue().get(SecurityConstants.TOKEN_PREFIX + token);
            redisTemplate.expire(SecurityConstants.TOKEN_PREFIX + userDto.getToken(),
                    300, TimeUnit.SECONDS);
            redisTemplate.expire(SecurityConstants.USER_ID_PREFIX + userDto.getId(),
                    300, TimeUnit.SECONDS);
            return userDto;
        }
        return null;
    }

    @Override
    public Boolean logout(String id) {
        if(StrUtil.isNotBlank(id)){
            String token = (String) redisTemplate.opsForValue().get(SecurityConstants.USER_ID_PREFIX + id);
            if(StrUtil.isNotBlank(token)){
                redisTemplate.delete(SecurityConstants.TOKEN_PREFIX + token);
            }
            redisTemplate.delete(SecurityConstants.USER_ID_PREFIX + id);
            return  true;
        }
        return  false;
    }
}
